package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.Attachment;
import com.sl.au.entity.Bid;
import com.sl.au.entity.BidRecord;
import com.sl.au.entity.Module;
import com.sl.au.entity.Quote;
import com.sl.au.entity.QuoteDevice;
import com.sl.au.entity.QuoteForeign;
import com.sl.au.entity.QuoteReplacement;
import com.sl.au.entity.User;
import com.sl.au.repository.BidRecordRepository;
import com.sl.au.service.ActivitiService;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.AuditNodeService;
import com.sl.au.service.BidService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.au.service.QuoteForeignService;
import com.sl.au.service.QuoteService;

@RestController
@RequestMapping(value = "/ui/bid")
public class BidController extends BaseController {

	@Autowired
	private BidService bidService;

	@Autowired
	OptionService optionService;

	@Autowired
	OperateLogService operateLogService;

	@Autowired
	QuoteForeignService quoteForeignService;

	@Autowired
	QuoteService quoteService;

	@Autowired
	AttachmentService attachmentService;

	@Autowired
	BidRecordRepository bidRecordRepository;

	@Autowired
	private ActivitiService activitiService;
	@Autowired
	AuditNodeService auditNodeService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView mv = this.createLayoutView("bid/bidindex");
		String name = "bidadmin";
		Module module = this.getPageModule(name);
		mv.addObject("module", module);
		return mv;
	}

	// 新增投标
	@RequestMapping(value = "bidadd", method = RequestMethod.GET)
	public ModelAndView bidAdd() {
		ModelAndView mv = this.createLayoutView("bid/bidadd");
		Account a = this.getMyAccount();
		String userName = a.getUser().getEmpLogin().getUserName();
		String superiorArea = a.getUser().getSaleArea().getSuperiorArea();
		String superior = a.getUser().getSaleArea().getSuperior();
		if (superior.equals("外贸处")) {
			mv.addObject("foreign", 1);
			mv.addObject("quoteType", "外贸价格单");
		} else {
			mv.addObject("common", 1);
			mv.addObject("quoteType", "普通价格单");
		}
		String bidType = "投标类型";
		String projectType = "项目类型";
		String cashType = "保证金方式";
		mv.addObject("yin", 1);
		mv.addObject("department", superiorArea);
		mv.addObject("bidTypes", optionService.getRepository().findByGroup(bidType));
		mv.addObject("projectTypes", optionService.getRepository().findByGroup(projectType));
		mv.addObject("cashTypes", optionService.getRepository().findByGroup(cashType));
		mv.addObject("userName", userName);
		mv.addObject("bidDate", new Date());
		return mv;
	}

	// 投标编辑
	@RequestMapping(value = "bidedit", method = RequestMethod.GET)
	public ModelAndView bidEdit() {
		ModelAndView mv = this.createLayoutView("bid/bidedit");
		String bidId = request.getParameter("id");
		Bid bid = bidService.getRepository().findById(bidId);
		String quoteType = bid.getQuoteType();
		if (quoteType.equals("外贸价格单")) {
			mv.addObject("foreign", 1);
		} else if (quoteType.equals("普通价格单")) {
			mv.addObject("common", 1);
		}
		mv.addObject("yin", 1);
		String department = "上级部门";
		String bidType = "投标类型";
		String projectType = "项目类型";
		String cashType = "保证金方式";
		mv.addObject("departments", optionService.getRepository().findByGroup(department));
		mv.addObject("bidTypes", optionService.getRepository().findByGroup(bidType));
		mv.addObject("projectTypes", optionService.getRepository().findByGroup(projectType));
		mv.addObject("cashTypes", optionService.getRepository().findByGroup(cashType));
		mv.addObject("bid", bid);
		return mv;
	}

	// 投标查看
	@RequestMapping(value = "bidsee", method = RequestMethod.GET)
	public ModelAndView bidSee() {
		ModelAndView mv = this.createLayoutView("bid/bid-see");
		String bidId = request.getParameter("id");
		Bid bid = bidService.getRepository().findById(bidId);
		String quoteType = bid.getQuoteType();
		if (quoteType.equals("外贸价格单")) {
			mv.addObject("foreign", 1);
		} else if (quoteType.equals("普通价格单")) {
			mv.addObject("common", 1);
		}
		String cashType = bid.getCashType();
		if (cashType.equals("保函")) {
			mv.addObject("baohan", 1);
		}
		mv.addObject("yin", 0);
		
		mv.addObject("bid", bid);
		return mv;
	}

	//// 保存投标
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public Map<String, Object> save(HttpServletRequest request, @RequestBody Bid bid) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		bid.setUser(user);
		System.out.println(bid.getCustomerId());
		Quote q = quoteService.getRepository().findOne(bid.getQuote().getId());
		QuoteForeign qf = quoteForeignService.getRepository().findOne(bid.getQuoteForeign().getId());
		bid.setQuote(q);
		bid.setQuoteForeign(qf);
		Bid oldBid = bidService.getRepository().findOne(bid.getId());
		if (oldBid != null) {
			String content = "编辑投标【" + bid.getName() + "】";
			operateLogService.log(user, "编辑投标", content);
		} else {
			String content = "新增投标【" + bid.getName() + "】";
			operateLogService.log(user, "新增投标", content);
		}
		bidService.getRepository().save(bid);
		String bidId = bid.getId();
		Date createTime = bid.getCreateTime();

		map.put("code", 0);
		map.put("bidId", bidId);
		map.put("createTime", createTime);
		return map;
	}

	//// 保存投标情况记录
	@RequestMapping(value = "saveRecord", method = RequestMethod.POST)
	public Map<String, Object> saveRecord(HttpServletRequest request, @RequestBody BidRecord bidRecord) {
		Map<String, Object> map = new HashMap<String, Object>();
		String bidId = bidRecord.getBid().getId();
		Bid bid = bidService.getRepository().findById(bidId);
		bidRecord.setBid(bid);
		bidRecordRepository.save(bidRecord);
		map.put("code", 0);
		map.put("bidId", bidId);
		return map;
	}

	// 删除投标
	@RequestMapping(value = "delBid", method = RequestMethod.GET)
	public Map<String, Object> delBid(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<Bid> bids = new ArrayList<Bid>();
		for (int i = 0; i < id.length; i++) {
			String bidId = id[i];
			Bid bid = new Bid();
			bid.setId(bidId);
			bids.add(bid);
			///// 删除与bidId相关的附件
			List<Attachment> attachments = new ArrayList<Attachment>();
			attachments = attachmentService.getRepository().findByParentId(bidId);
			attachmentService.getRepository().deleteInBatch(attachments);
			///// 删除与bidId相关的投标记录
			bidRecordRepository.deleteBidRecord(bidId);
		}

		///// 插入删除日志
		Account a = this.getMyAccount();
		User user = a.getUser();
		for (Bid b : bids) {
			Bid old = bidService.getRepository().findOne(b.getId());
			String content = "删除投标【" + old.getName() + "】";
			operateLogService.log(user, "删除投标", content);
		}
		bidService.getRepository().deleteInBatch(bids);
		map.put("code", 0);
		return map;
	}

	/// 删除投标情况记录
	@RequestMapping(value = "delBidRecord", method = RequestMethod.GET)
	public Map<String, Object> delBidRecord(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<BidRecord> bidRecords = new ArrayList<BidRecord>();
		for (int i = 0; i < id.length; i++) {
			String recordId = id[i];
			BidRecord bidRecord = new BidRecord();
			bidRecord.setId(recordId);
			bidRecords.add(bidRecord);
		}
		bidRecordRepository.deleteInBatch(bidRecords);
		map.put("code", 0);
		return map;
	}

	// 投标反馈
	@RequestMapping(value = "backbid", method = RequestMethod.GET)
	public ModelAndView backbid() {
		ModelAndView mv = this.createLayoutView("bid/bidback");
		String bidId = request.getParameter("id");
		Bid bid = bidService.getRepository().findById(bidId);
		String backType = "投标反馈类型";
		mv.addObject("backTypes", optionService.getRepository().findByGroup(backType));
		mv.addObject("bid", bid);
		return mv;
	}

	/**
	 * 提交投标审批
	 * 
	 * @return
	 */
	@RequestMapping(value = "audit/{bidId}")
	public ModelAndView newContract(@PathVariable String bidId) {
		ModelAndView modelAndView = this.createLayoutView("bid/bid-audit");
		Bid bid = bidService.getRepository().getOne(bidId);
		String quoteType = bid.getQuoteType();
		if (quoteType.equals("外贸价格单")) {
			modelAndView.addObject("foreign", 1);
		} else if (quoteType.equals("普通价格单")) {
			modelAndView.addObject("common", 1);
		}
		String cashType = bid.getCashType();
		if (cashType.equals("保函")) {
			modelAndView.addObject("baohan", 1);
		}
		modelAndView.addObject("yin", 0);
		modelAndView.addObject("bid", bid);
		modelAndView.addObject("bidName", bid.getName());
		modelAndView.addObject("bidId", bid.getId());
		return modelAndView;
	}

	/**
	 * 查看审批的投标内容
	 * 
	 * @return
	 */
	@RequestMapping(value = "audit-view/{taskId}/{bidId}")
	public ModelAndView auditReadonly(@PathVariable String taskId, @PathVariable String bidId) {
		ModelAndView modelAndView = this.createLayoutView("bid/bid-audit-view");
		Bid bid = bidService.getRepository().getOne(bidId);
		String quoteType = bid.getQuoteType();
		if (quoteType.equals("外贸价格单")) {
			modelAndView.addObject("foreign", 1);
		} else if (quoteType.equals("普通价格单")) {
			modelAndView.addObject("common", 1);
		}
		String cashType = bid.getCashType();
		if (cashType.equals("保函")) {
			modelAndView.addObject("baohan", 1);
		}
		modelAndView.addObject("yin", 0);
		modelAndView.addObject("bid", bid);
		modelAndView.addObject("bidName", bid.getName());
		modelAndView.addObject("bidId", bid.getId());
		modelAndView.addObject("taskId", taskId);
		modelAndView.addObject("auditnodes",
				auditNodeService.getRepository().getNodesById(bid.getProcessInstId(), bidId));
		return modelAndView;
	}

	/**
	 * 查看审批的投标内容JSON
	 * 
	 * @return
	 */
	@RequestMapping(value = "audit-view/{taskId}/{bidId}/json", method = RequestMethod.GET)
	public Map<String, Object> auditReadonlyJSON(@PathVariable String taskId, @PathVariable String bidId) {
		Map<String, Object> map = new HashMap<>();
		Bid bid = bidService.getRepository().findOne(bidId);
		String quoteType = bid.getQuoteType();
		if (quoteType.equals("外贸价格单")) {
			map.put("isForeign", 1);
			if (null != bid.getQuoteForeign()) {
				String quoteId = bid.getQuoteForeign().getId();
				QuoteForeign quoteForeign=quoteForeignService.getRepository().findOne(quoteId);
				List<QuoteDevice> quoteDevices = quoteForeignService.getQuoteDevice(0, Integer.MAX_VALUE, quoteId,
						"createTime", "desc");
				List<QuoteReplacement> quoteReplacements = quoteForeignService.getQuoteReplacement(0, Integer.MAX_VALUE,
						quoteId, "createTime", "desc");
				map.put("pumps", quoteDevices);
				map.put("others", quoteReplacements);
				map.put("quoteForeign", quoteForeign);
			}
		} else if (quoteType.equals("普通价格单")) {
			map.put("isCommon", 1);
			if (null != bid.getQuote()) {
				String quoteId = bid.getQuote().getId();
				Quote quote=quoteService.getRepository().findOne(quoteId);
				List<QuoteDevice> quoteDevices = quoteService.getQuoteDevice(0, Integer.MAX_VALUE, quoteId,
						"createTime", "desc");
				List<QuoteReplacement> quoteReplacements = quoteService.getQuoteReplacement(0, Integer.MAX_VALUE,
						quoteId, "createTime", "desc");
				map.put("pumps", quoteDevices);
				map.put("others", quoteReplacements);
				map.put("quote", quote);
			}
		}
		String cashType = bid.getCashType();
		if (cashType.equals("保函")) {
			map.put("hasBaohan", 1);
		}

		map.put("bid", bid);
		map.put("taskId", taskId);
		map.put("auditNodes", auditNodeService.getAll(bid.getProcessInstId(), bidId));
		return map;
	}

	///// 获得一个投标信息
	@RequestMapping(value = "getBid", method = RequestMethod.GET)
	public Map<String, Object> getBid(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String bidId = request.getParameter("bidId");
		Bid bid = bidService.getRepository().findById(bidId);
		Quote q = bid.getQuote();
		QuoteForeign qf = bid.getQuoteForeign();
		if (q != null) {
			map.put("quote", q);

		} else if (qf != null) {
			map.put("foreign", qf);

		}
		return map;
	}

	//// 获得投标的信息
	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String auditState = request.getParameter("auditState");//审核状态
		String name = "bidadmin";
		Module module = this.getPageModule(name);
		String dataFilter = module.getDataFilter();
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String superior = a.getUser().getSaleArea().getSuperior();
		String areaId = a.getUser().getSaleArea().getId();
		Map<String, String> condition = new HashMap<String, String>();
		condition.put("auditState", auditState);
		condition.put("key", key);
		condition.put("dataFilter", dataFilter);
		condition.put("superior", superior);
		condition.put("areaId", areaId);
		condition.put("userId", userId);
		List<Bid> bids = bidService.getBid(start, length, condition);
		long count = bidService.getBidCount(condition);
		map.put("data", bids);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	//// 获得投标情况的信息
	@RequestMapping(value = "getbidrecord", method = RequestMethod.GET)
	public Map<String, Object> getBidRecord(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String bidId = request.getParameter("bidId");
		List<BidRecord> bidRecords = bidService.getBidRecord(start, length, bidId);
		long count = 0;
		count = bidRecordRepository.getCount(bidId);
		map.put("data", bidRecords);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 发起投标流程
	 * 
	 * @param bidId
	 * @return
	 */

	@RequestMapping(value = "/audit/{bidId}", method = RequestMethod.POST)
	public Map<String, Object> submitAudit(@PathVariable String bidId, HttpServletRequest request) {

		Map<String, Object> map = new HashMap<>();
		Map<String, String> variables = new HashMap<>();
		Account account = this.getMyAccount();
		int code = -1;

		String auditorNumber = request.getParameter("auditorNumber");
		String auditor1 = request.getParameter("auditor1");
		String auditor2 = request.getParameter("auditor2");
		String auditor3 = request.getParameter("auditor3");
		String auditor4 = request.getParameter("auditor4");
		String auditor5 = request.getParameter("auditor5");
		String auditor6 = request.getParameter("auditor6");
		String auditor7 = request.getParameter("auditor7");
		String auditor8 = request.getParameter("auditor8");
	
		String name = request.getParameter("name");
		Bid bid = bidService.getRepository().getOne(bidId);
		/*if(bid.getQuote() != null)
			System.out.println(bid.getQuote().getId() + "," );
		if(bid.getQuoteForeign() != null)
			System.out.println(bid.getQuoteForeign().getId());*/
		if (null != bidId && null != account && null != auditorNumber && (bid.getQuote() != null || bid.getQuoteForeign() != null)) {
			// 放置流程实例变量
			variables.put("starter", account.getUser().getId());
			variables.put("auditor1", auditor1);
			variables.put("auditor2", auditor2);
			variables.put("auditor3", auditor3);
			variables.put("auditor4", auditor4);
			variables.put("auditor5", auditor5);
			variables.put("auditor6", auditor6);
			variables.put("auditor7", auditor7);
			variables.put("auditor8", auditor8);
			
			variables.put("auditorNumber", auditorNumber);
			variables.put("auditState", "已提交");
			variables.put("entityName", "bid");
			variables.put("entityId", bidId);
			variables.put("processDefinitionName", "投标");
			ProcessInstance pInst = activitiService.startProcessInstance("bid", account.getUser().getId(), variables);
			// 流程启动后，将其实例相关信息保存到业务实体中，以便查询
			bidService.saveProcessStart(bidId, pInst);
			code = 0;

		}
		map.put("code", code);
		return map;
	}

	/// 获得一个部门的一个状态下的普通报价单
	@RequestMapping(value = "getAduitQuote", method = RequestMethod.GET)
	public Map<String, Object> getAduitQuote(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		long count = 0;
		String key = request.getParameter("key");
		String auditState = request.getParameter("auditState");
		Account a = this.getMyAccount();
		String superior = a.getUser().getSaleArea().getSuperior();
		List<Quote> quotes = quoteService.getQuoteInState(start, length, key, auditState, superior);
		count = quoteService.getRepository().passQuoteCount(key, auditState, superior);
		map.put("data", quotes);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/// 获得一个部门的一个状态下的外贸报价单
	@RequestMapping(value = "getAduitForeignQuote", method = RequestMethod.GET)
	public Map<String, Object> getAduitForeignQuote(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		long count = 0;
		String key = request.getParameter("key");
		String auditState = request.getParameter("auditState");
		Account a = this.getMyAccount();
		String superior = a.getUser().getSaleArea().getSuperior();
		List<QuoteForeign> quotes = quoteForeignService.getForeignQuoteInState(start, length, key, auditState,
				superior);
		count = quoteForeignService.getRepository().getAuditQuoteCount(key, auditState, superior);
		map.put("data", quotes);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
}
